package com.yao.h2demo.server;

import lombok.extern.slf4j.Slf4j;
import org.h2.tools.Server;

import java.sql.SQLException;

/**
 * 创建h2的TCP的server
 *
 * @author yys1892
 */
@Slf4j
public class TcpServer {
    private Server server;

    public TcpServer() throws SQLException {
//     Supported options are:
//      -tcpPort, -tcpSSL, -tcpPassword, -tcpAllowOthers, -tcpDaemon,
//      -trace, -ifExists, -ifNotExists, -baseDir, -key.
        // 创建TCP的server，可以通过tcp进行连接
        this.server = Server.createTcpServer(
                //指定端口
                "-tcpPort", "8088",
                //允许其他主机连接
                "-tcpAllowOthers",
                //设置为守护进程
//                "-tcpDaemon",
                //数据的存储目录
                "-baseDir", "data",
                //连上之后自动创建数据库如果不存在
                "-ifNotExists"
//                "-tcpPassword","Aa123456"
        );
        log.warn("create h2 server listen on port:{}", 8088);
        // server关闭时的处理
        server.setShutdownHandler(() -> {
            log.warn("h2 server is shutting down");
        });
        start();
//      Supported options are:
//      -webPort, -webSSL, -webAllowOthers, -webDaemon,
        //创建web管理控制台 ，必须先启动H2server实例
        Server.createWebServer(
                "-webPort", "8089",
                "-webAllowOthers",
                "-webDaemon").start();
        log.warn("start h2 web server");
    }

    private void start() throws SQLException {
        server.start();
        // 检查是否运行 并记录错误
        while (!server.isRunning(true)) {
            log.info("h2 server is not ready");
            // 让出cpu时间，让线程变成就绪状态，重新抢夺cpu时间
            Thread.yield();
        }
        log.warn("h2 server start");
    }

}
